﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
using System.Windows.Forms;
using LOLHelper.constant;
using LOLHelper.Properties;
using LOLHelper.utils;
using Newtonsoft.Json.Linq;

namespace LOLHelper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 端口号
        /// </summary>
        private string port;

        /// <summary>
        /// 令牌
        /// </summary>
        private string token;

        /// <summary>
        /// 获取 port 和 password 的命令
        /// </summary>
        private string command = "WMIC PROCESS WHERE name=\"LeagueClientUx.exe\" GET commandline";

        /// <summary>
        /// 英雄名和id的映射
        /// </summary>
        private Dictionary<string, int> nameMapIdDict = new Dictionary<string, int>();

        /// <summary>
        /// id 和 英雄信息的映射
        /// </summary>
        private Dictionary<int, JToken> idMapHeroInfoDict = new Dictionary<int, JToken>();

        /// <summary>
        /// 所有的英雄名字
        /// </summary>
        List<string> heroNameList = new List<string>();

        private string heroName = "";

        [DllImport("kernel32.dll")]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filepath);

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(string section, string key, string def,
            StringBuilder returnvalue, int buffersize, string filepath);

        private void FormLOLHelper_Load(object sender, EventArgs e)
        {
            //获取cmd.exe程序
            var startInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            //设置启动的一些参数
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.CreateNoWindow = true;
            //获取Process类的新实例
            var myProcess = new System.Diagnostics.Process();
            myProcess.StartInfo = startInfo;
            //启动 cmd.exe
            myProcess.Start();
            // 输入命令
            myProcess.StandardInput.WriteLine(command);
            myProcess.StandardInput.WriteLine("exit");
            StreamReader reader = myProcess.StandardOutput;
            string strOuput = reader.ReadToEnd();
            reader.Close();
            myProcess.WaitForExit();
            myProcess.Close();

            // 规则匹配
            Regex portRegex = new Regex("--app-port=([0-9]*)");
            Regex tokenRegex = new Regex("--remoting-auth-token=([\\w-]*)");
            port = portRegex.Match(strOuput).Value;
            token = tokenRegex.Match(strOuput).Value;

            // 工具类初始化
            if (token != "" || port != "")
            {
                HttpUtil.password = token.Split('=')[1];
                HttpUtil.port = port.Split('=')[1];
                var result = HttpUtil.HttpRequset(ConstantLOLAPI.OWNED_CHAMPIONS_MINIMAL);
                InitComBoxAndPicBox(result);
            }
            else
            {
                MessageBox.Show("请以【 管理员身份 】运行此程序或先打开【 LOL客户端 】");
                Application.Exit();
            }
        }


        private void InitComBoxAndPicBox(string heroInfos)
        {
            var jArray = JArray.Parse(heroInfos);
            foreach (var jHero in jArray.Children())
            {
                // 初始化 combox 的值，构建 英雄名称 和 id 的映射
                this.cobxHeroName.Items.Add(jHero[ConstantLOLField.NAME].ToString());
                nameMapIdDict.Add(jHero[ConstantLOLField.NAME].ToString(), (int) jHero[ConstantLOLField.ID]);

                this.cobxHeroName.Items.Add(jHero[ConstantLOLField.ALIAS].ToString());
                nameMapIdDict.Add(jHero[ConstantLOLField.ALIAS].ToString(), (int) jHero[ConstantLOLField.ID]);

                this.cobxHeroName.Items.Add(jHero[ConstantLOLField.TITLE].ToString());
                nameMapIdDict.Add(jHero[ConstantLOLField.TITLE].ToString(), (int) jHero[ConstantLOLField.ID]);
                // 构建 id 和 英雄信息的映射
                idMapHeroInfoDict.Add((int) jHero[ConstantLOLField.ID], jHero);

                heroNameList.Add(jHero[ConstantLOLField.NAME].ToString());
                heroNameList.Add(jHero[ConstantLOLField.ALIAS].ToString());
                heroNameList.Add(jHero[ConstantLOLField.TITLE].ToString());
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.timerAccept.Start();
            this.btnStart.Text = "已开启";
            this.btnStop.Enabled = true;
            this.btnStart.Enabled = false;
        }

        private void cobxHeroName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int id = nameMapIdDict[this.cobxHeroName.SelectedItem.ToString()];
                var jToken = idMapHeroInfoDict[id];
                heroName = this.cobxHeroName.SelectedItem.ToString();
                this.piBoxAvatar.Image = HttpUtil.GetHeroAvatar(jToken[ConstantLOLField.SQUARE_PORTRAIT_PATH].ToString());
            }
            catch (Exception exception)
            {
                heroName = "";
                this.piBoxAvatar.Image = Resources.英雄联盟;
            }

        }

        private void timerAccept_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                HttpUtil.HttpRequset(ConstantLOLAPI.ACCEPT, null, null, "POST");
            }
            catch
            {
                // ignored
            }

            try
            {
                if (heroName != "")
                {
                    var id = nameMapIdDict[heroName];

                    // 获取当前用户的 summerid
                    var userInfo = HttpUtil.HttpRequset(ConstantLOLAPI.LOGIN_SESSION);
                    var userJson = JObject.Parse(userInfo);
                    var summerId = userJson.Value<long>(ConstantLOLField.SUMMONER_ID);

                    // 获取cellId
                    var selectSession = HttpUtil.HttpRequset(ConstantLOLAPI.SELECT_SESSION);
                    var sessionJson = JObject.Parse(selectSession);
                    var myTeam = sessionJson.Value<JArray>(ConstantLOLField.MY_TEAM);
                    int cellId = 0;
                    foreach (var jToken in myTeam)
                    {
                        if (jToken.Value<long>(ConstantLOLField.SUMMONER_ID) == summerId)
                        {
                            cellId = jToken.Value<int>(ConstantLOLField.CELL_ID);
                            break;
                        }
                    }

                    // 获取 actions
                    var actionsArray = sessionJson.Value<JArray>(ConstantLOLField.ACTIONS);
                    var jArray = actionsArray[0].Value<JArray>();
                    JToken postData = null;
                    foreach (var jToken in jArray)
                    {
                        if (jToken.Value<int>(ConstantLOLField.ACTOR_CELL_ID) == cellId)
                        {
                            postData = jToken;
                            break;
                        }
                    }

                    postData[ConstantLOLField.CHAMPION_ID] = id;
                    var idValue = postData.Value<int>(ConstantLOLField.ID);

                    HttpUtil.HttpRequset(ConstantLOLAPI.SELECT_SESSION_ACTIONS + "/" + idValue, null,
                        postData.ToString(), "PATCH");
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.timerAccept.Stop();
            this.btnStart.Text = "自动接受";
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
        }

        private void cobxHeroName_TextUpdate(object sender, EventArgs e)
        {
            //输入key之后返回的关键词
            List<string> listNew = new List<string>();
            this.cobxHeroName.Items.Clear();
            //清空listNew
            listNew.Clear();
            //遍历全部备查数据
            foreach (var item in heroNameList)
            {
                if (item.Contains(this.cobxHeroName.Text))
                {
                    //符合，插入ListNew
                    listNew.Add(item);
                }
            }

            //combobox添加已经查询到的关键字
            this.cobxHeroName.Items.AddRange(listNew.ToArray());
            //设置光标位置，否则光标位置始终保持在第一列，造成输入关键词的倒序排列
            this.cobxHeroName.SelectionStart = this.cobxHeroName.Text.Length;
            //保持鼠标指针原来状态，有时鼠标指针会被下拉框覆盖，所以要进行一次设置
            Cursor = Cursors.Default;
            //自动弹出下拉框
            this.cobxHeroName.DroppedDown = true;
        }
    }
}